<?php

namespace bee;

/**
 *
 * @param string $datum
 * @return string
 * @author DY damir.zelenika@gmail.com
 */
function YMDdmy($datum)
{	$pomoc = substr($datum, 8, 2) . "/" . substr($datum, 5, 2) . "/" . substr($datum, 0, 4) . substr($datum, 10, 32);
	return $pomoc;
}

function YMDdmySh($datum, $onlyDate)
{	$pomoc = substr($datum, 8, 2) . "." . substr($datum, 5, 2) . "." . substr($datum, 0, 4) . (!$onlyDate?substr($datum, 10, 32) :"");
return $pomoc;
}

function dmyYMD($datum)
{
  if(strlen($datum) < 10)
  {
  	return "";
  }
  $pomoc = substr($datum, 6, 4) . "-" . substr($datum, 3, 2) . "-" . substr($datum, 0, 2) . substr($datum, 10, 32);
	return $pomoc;
}

function YMDmdy($datum)
{
  //die("+$datum+");
  if(strlen($datum) < 10)
  {
    return "";
  }
  $pomoc = substr($datum, 5, 2) . "/" . substr($datum, 8, 2) . "/" . substr($datum, 0, 4) . substr($datum, 10, 32);
  return $pomoc;
}
function mdyYMD($datum)
{
  if(strlen($datum) < 10)
  {
    return "";
  }
  $pomoc = substr($datum, 6, 4) . "-" . substr($datum, 0, 2) . "-" . substr($datum, 3, 2) . substr($datum, 10, 32);
  return $pomoc;
}

function myYMD($datum)
{
  if(strlen($datum) < 7)
  {
    return "";
  }
  $pomoc = substr($datum, 3, 4) . "-" . substr($datum, 0, 2) . "-01";
  return $pomoc;
}

function YMDmy($datum)
{
  if(strlen($datum) < 7)
  {
    return "";
  }
  $pomoc = substr($datum, 5, 2) . "/" . substr($datum, 0, 4);
  return $pomoc;
}

function YMD($datum)
{ $pomoc = substr($datum, 5, 2);
return $pomoc;
}



function addDays($YMDday, $numDays)
{ return date("Y-m-d H:i:s", strtotime($YMDday)+ 86400 * $numDays);
}

function dateValidate($date)
{ if($date)
  { if($value = date_create($date))
    { $value = date_format($value, "Y-m-d H:i:s");
    } else
    { $value = "";
    }
  }
  else
  { $value = "";
  }
//print_r($value);
  return $value;
}

class serror //extends object
{	public $err_description;
	public $err_code;
	public $err_type;
	public $err_level;
	public function setErrorLevel($level)
	{ if($level > $this->err_level)
	  {  $this->err_level = $level;
	  }
	}
}

function isInGroup($korisnik, $grupa)
{	$gr_kor = new gr_usr();
	$gr_kor->korisnik = $korisnik;
	$gr_kor->grupa = $grupa;
	$rs_gr_kor = new rowSet($gr_kor);
	if($rs_gr_kor->getRow($gr_kor))
	{	return true;
	}	else
	{	return false;
	}
}

function owns_acces($user, $page, $action = "", $useDbProcs = true)
{ $cfg = config::getInstance();

  if(app::getInstance()->isPublicForm())
  { return true;
  }
  /**
   * @todo logic changed. if db procs are used they should be changed.
   * if a action parameter is  given, then should be controlled
   */
  if($cfg->sys_USE_DB_PROCS)
  {	$db = db::getInstance();
    return $db->execSQL(new afterWhere("SELECT dbo.ownsAccess(?, ?, ?)", array($user, $page, $action)));
  } else
  { //----------------------8<--------------if()---------

    if($app_arr_job = processor::getUserJobs())
    {
      //die(print_r($app_arr_job));
      $allow = false;
  		foreach ($app_arr_job as $job)
  		{	if($job["per_den"] == 1)
  			{	//if((!$job["sys_action"] && $job["sys_page"] == $page) || ($job["sys_action"] == $action && $job["sys_page"] == $page))
  			  if($job["sys_action"] == $action && $job["sys_page"] == $page)
  			  {	$allow = true;
  				}
  			}	else if($job["per_den"] == -1)
  			{	//if(!$job["sys_action"] && $job["sys_page"] == $page) || ($job["sys_action"] == $action && $job["sys_page"] == $page))
  			  if($job["sys_action"] == $action && $job["sys_page"] == $page)
  				{	return false;
  				}
  			}
  		}
  		if($allow)
  		{	return true;
  		}
    }
		return false;
  }
}

function elipsis($text, $length, $wrap_width = 1024)
{	if(strlen($text) > $length)
	{	$text = substr($text, 0, $length - 3) . "...";
	}
	return wordwrap($text, $wrap_width," ", true);

}

function getListByRange($range,  $key = "lvalue", $value = "ltext")
{	$row = new lists();
	$row->status = 1;
	$row->range = $range;
	$rs = new rowSet($row, new afterWhere(" ORDER BY ordnr"));
	$retArr = array();
	while ($rs->getRow($row))
	{	$retArr[$row->$key] = $row->$value;
	}
	return  $retArr;
}

function getListByRangeName($rangeName,  $key = "lvalue", $value = "ltext")
{
  $row = new lists();
  $row->status = 1;
  $row->rangename = $rangeName;
  $rs = new rowSet($row, new afterWhere(" ORDER BY ordnr"));
  $retArr = array();
  while ($rs->getRow($row))
  { $retArr[$row->$key] = $row->$value;
  }
  return  $retArr;
}


function getArrValueByKey(&$arr, $key, $default = "")
{ if(isset($arr[$key]))
  { return $arr[$key];
  } else
  { return $default;
  }
}

function aggregateArray(array $arr, $groupField, $valueField, $aggregationType = "sum", $sortAscDdesc = "")
{	reset($arr);
	$oldKey 		= "";
	$ret_arr 		= array();
	$row				= array();
	$init 			= 1;
	$tmp_arr 		= array();
	foreach ($arr as $row)
	{	switch($aggregationType)
		{	case "count":
				@$tmp_arr[$row[$groupField]]++;
				break;
			case "avg":
				@$tmp_arr[$row[$groupField]]["sum"] += $row[$valueField];
				@$tmp_arr[$row[$groupField]]["count"]++;
				break;
			case "sum":
				@$tmp_arr[$row[$groupField]] += $row[$valueField];
				break;
			case "min":
				if($row[$valueField] < (@$tmp_arr[$row[$groupField]] ? $tmp_arr[$row[$groupField]] : ($row[$valueField] + 1)))
				{	$tmp_arr[$row[$groupField]] = $row[$valueField];
				}
				break;
			case "max":
				if($row[$valueField] > (@$tmp_arr[$row[$groupField]] ? $tmp_arr[$row[$groupField]] : ($row[$valueField] - 1)))
				{	$tmp_arr[$row[$groupField]] = $row[$valueField];
				}
				break;
			default:
		}
	}
	if($sortAscDdesc == "asc")
	{	asort($tmp_arr);
	}	elseif($sortAscDdesc == "desc")
	{	arsort($tmp_arr);
	}
	if($aggregationType == "avg")
	{	foreach($tmp_arr as $key => $val)
		{	$ret_arr[] = array($groupField => $key, $valueField => $val["sum"] / $val["count"]);
		}
	}
	else
	{	foreach($tmp_arr as $key => $val)
		{	$ret_arr[] = array($groupField => $key, $valueField => $val);
		}
	}
	return $ret_arr;
}

function raw2hex($string)
{	$ret = "";
	$d = strlen($string);
	for($i = 0; $i < $d; $i++)
	{	$sh = "00" . dechex(ord(substr($string, $i)));
		$ret .= substr($sh, strlen($sh)-2);
	}
	return $ret;
}

function reachedLimit(user $user = null, $tip = 1) // ovo nije za core **********************
{	if(config::getInstance()->sys_USE_DB_PROCS)
  { return db::getInstance()->execSQL(new afterWhere("SELECT dbo.reachedLimit(?, ?)", array($user->id, $tip)));
  }
	global $app_USER;
	$client_id = $user->id;
	if(!$user)
	{	$user = $app_USER;
	}
	if($tip == 2)
	{	$kom_user = new org_unit();
		$kom_user->SELECT($user->org_id);
		$user = $kom_user;
	}

	$arr_limit = array();
	$limit = new \limit();
	$limit->status = 1;
	$limit->tip = $tip;
	$rs_limit = new rowSet($limit);
	while($rs_limit->getRow($limit))
	{	$row = array();
		$row["interval"] = $limit->interval;
		$row["broj"] = $limit->broj;
		$row["iznos"] = $limit->iznos;
		$row["status"] = $limit->status;
		$arr_limit[$limit->id] = $row;
	}

	$limit_client = new \limit_client();
	$limit_client->client = $user->id;
	$limit_client->tip = $tip;
	$rs_limit_client = new rowSet($limit_client);
	while($rs_limit_client->getRow($limit_client))
	{	if(isset($arr_limit[$limit_client->limit]))
	  { $promet = new \promet();
			$promet->client = $client_id;
			$rs_promet = new rowSet($promet,
			  new afterWhere( " AND DateDiff(second, vrijeme, GetDate() ) < :razmak ",
			                  array("razmak" => $arr_limit[$limit_client->limit]["interval"])));

			if(@$arr_limit[$limit_client->limit]["broj"] && $rs_promet->num_rows >= @$arr_limit[$limit_client->limit]["broj"])
			{	return $limit_client->limit;
			}	else
			{	$sum = 0;
				while ($rs_promet->getRow($promet))
				{	$kod = new \kod();
					$kod->SELECT($promet->kod);
					$sum += $kod->cijena;
				}
				if(@$arr_limit[$limit_client->limit]["iznos"] && $sum >= @$arr_limit[$limit_client->limit]["iznos"])
				{	return  $limit_client->limit;
				}
			}
    }
	}
	return 0;
}

function ownsClient($client_id)
{	if(!$client_id)
	{	return false;
	}	else
	{ $client = new user();
		$client->SELECT($client_id);
		if($client->org_id == app::getInstance()->getUser()->org_id)
		{ return true;
		} else if(!app::getInstance()->getClientFilter())
		{ return true;
	  } else
	  { return false;
	  }
	}
	return false;
}

function getSeqEncripted()
{	$param = new params();
	$param->SELECT("PDF_sequence");
	$seq = substr(md5($param->value), 0, 16);
	$param->value = $param->value + 1;
	$param->UPDATE();
	return $seq;
}
/**
 * @todo kreirati klasu tipa report koja ovo odrađuje
 * @param $rptDefFile
 * @param $seq
 * @return unknown_type
 */
function generateReport($rptDefFile = "", &$seq = "", $options = NULL)
{	/**
 * @var object config $cfg
 */
  $cfg = config::getInstance();
	//$DSDoc = DOMSQLDocument::getInstance();
	$DSDoc = XMLDataHub::getInstance();
	global $app_USER;
	$FOprocessor = 	new \XSLTProcessor();
	$FOss = 				new \DOMDocument();
	$FOxsl = 				new \DOMDocument();


	$dn = "";
	$rn= "";
	if(isset($options["downloadName"]))
	{ $dn = $options["downloadName"];
	} else if($rptDefFile)
	{ $dn = $rptDefFile;
	} else if(isset($_REQUEST["sys_page"]))
	{ $dn = $_REQUEST["sys_page"];
	} else if(isset($_REQUEST["__form"]))
  { $dn = $_REQUEST["__form"];
  } else if(isset($_REQUEST["special_page"]))
  { $dn = $_REQUEST["special_page"];
  } else if(isset($_REQUEST["special_app_page"]))
  { $dn = $_REQUEST["special_app_page"];
  } else
  { $dn = "report";
  }
  if($rptDefFile)
  { $rn = $rptDefFile;
  } else if(isset($_REQUEST["sys_page"]))
  { $rn = $_REQUEST["sys_page"];
  } else if(isset($_REQUEST["__form"]))
  { $rn = $_REQUEST["__form"];
  } else if(isset($_REQUEST["special_page"]))
  { $rn = $_REQUEST["special_page"];
  } else if(isset($_REQUEST["special_app_page"]))
  { $rn = $_REQUEST["special_app_page"];
  }

  $seq = getSeqEncripted();

  //echo "*" . $cfg->sys_FOP_PATH . "/$seq" . "*";

  mkdir($cfg->sys_FOP_PATH . "/$seq");
  $FOss->load($cfg->sys_REPORTS_PATH . "/$rn.xsl");
  /*
  if($rptDefFile)
  { $FOss->load($cfg->sys_REPORTS_PATH . "/$rptDefFile.xsl");
  }	else if(isset($_REQUEST["sys_page"]))
  {
    $FOss->load($cfg->sys_REPORTS_PATH . "/rpt_{$_REQUEST["sys_page"]}.xsl");
  } else if(isset($_REQUEST["__form"]))
  {
    $FOss->load($cfg->sys_REPORTS_PATH . "/rpt_{$_REQUEST["__form"]}.xsl");
  }
  */
  $FOprocessor->importStylesheet($FOss);
  $FOxsl = 	$FOprocessor->transformToXml($DSDoc);
  $DSDoc->setVariable("sys_seq", $seq);



  $dat = fopen($cfg->sys_FOP_PATH . "/$seq/$rn.fo", "w");
	fputs($dat, $FOxsl);
	fclose($dat);

	$download 									= new download();
	//$download->client 					= app::getInstance()->getUser()->id;// $app_USER->id;
	$download->content_type 		= "application/pdf";
	$download->created					= date("Y-m-d H:i:s");
	$download->down_name 				= "$dn.pdf";
	$download->expire						= date("Y-m-d H:i:s", time() + 30 * 60);
	$download->file_name 				= $cfg->sys_FOP_PATH . "/$seq/$dn.pdf";
	$download->INSERT();

	//echo "shell_exec(fop -fo {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$rn.fo -pdf {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$dn.pdf)";
	if((isset($options["execShell"]) ?: false) == true)
	{ shell_exec("cd /home/sportiw/bee2OS/lib/ext/fop/build;ls");
	//echo shell_exec("ls -al >> /home/sportiw/log.txt");
	//echo shell_exec("rm -rf /home/sportiw/siw/tmp/pdf_tmp/* >> /home/sportiw/log.txt");
	  /**
	   * @todo treba isparametrizirati putanju of fopa (ubačeno na brzinu)
	   */


$echo= "cd /home/sportiw/bee2OS/lib/ext/fop/build;java -jar fop.jar -fo {$cfg->sys_FOP_PATH}/$seq/$rn.fo -pdf {$cfg->sys_FOP_PATH}/$seq/$dn.pdf";
//echo $echo;

	  //echo shell_exec("cd /home/sportiw/bee2OS/lib/ext/fop/build;java -jar fop.jar -fo {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$rn.fo -pdf {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$dn.pdf");
//shell_exec($echo);
    shell_exec($echo);
	  //die("123");
	} else
	{ //shell_exec("fop -fo {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$rn.fo -pdf {$cfg->sys_TMP_PATH}/pdf_tmp/$seq/$dn.pdf");
	}

	if(isset($_REQUEST["sys_page"]) || isset($_REQUEST["__form"]) || isset($_REQUEST["special_app_page"]) || isset($_REQUEST["__ajax"]))
	{ return "index.php?special_app_page=download_file.php&download_id=" . $download->id;
	} else if(isset($_REQUEST["special_page"]))
	{ return "index.php?special_page=download_file.php&download_id=" . $download->id;
	}

}
/**
 * @todo trebala bi biti metoda u nekoj report klasi
 * @param unknown_type $XLSClass
 * @param unknown_type $seq
 * @return unknown_type
 */
function generateXLS($XLSClass = "", $seq, $format = "2003")
{	$cfg = config::getInstance();
	//$DSDoc = DOMSQLDocument::getInstance();
	$DSDoc = XMLDataHub::getInstance();
	////global $state;
	//global $app_USER;
	//global $form;

	$xPath = new \DOMXPath($DSDoc);
	$template_path = $cfg->sys_REPORTS_PATH . "/" . (isset($_REQUEST["sys_page"])? $_REQUEST["sys_page"] : $_REQUEST["__form"])  . ".xlsx";
	if(!$XLSClass)
	{	$XLSClass = "xrClass";
	}
	$xrClass = 	new $XLSClass($template_path);
	$rows = $xPath->query("/form/tables/__table__/row");
	foreach ($rows as $row)
	{	$xrClass->addRow($row);
	}

	$xrClass->addFinalSum(isset($row) ? $row : null);
  if(!is_dir($cfg->sys_FOP_PATH . "/$seq"))
  { mkdir($cfg->sys_FOP_PATH . "/$seq");
  }
  $xrClass->save($cfg->sys_FOP_PATH . "/$seq/" .(isset($_REQUEST["sys_page"])? $_REQUEST["sys_page"] : $_REQUEST["__form"]));
//$x//rClass->
	$download 									= new download();
	$download->client 					= app::$user->id; // $app_USER->id;
	$download->content_type 		= "application/vnd.ms-excel";
	$download->created					= date("Y-m-d H:i:s");
	$download->down_name 				= "" . (isset($_REQUEST["sys_page"])? $_REQUEST["sys_page"] : $_REQUEST["__form"]) . ".xls";
	$download->expire						= date("Y-m-d H:i:s", time() + 1800);
	$download->file_name 				= $cfg->sys_FOP_PATH . "/{$seq}/" . (isset($_REQUEST["sys_page"])? $_REQUEST["sys_page"] : $_REQUEST["__form"]) . ".xls";
	$download->INSERT();
	return "index.php?special_app_page=download_file.php&download_id=" . $download->id;
}

define("TEXT_XML", "text/xml");
define("IMAGE_PNG", "image/png");
define("APPLI_PDF", "application/PDF");
define("APPLI_XLS", "application/vnd.ms-excel");
/**
 * @todo povezati sa datotekom download_file u klasu download
 * @param $file_name
 * @param $down_name
 * @param $content_type
 * @return unknown_type
 */
function createDownload($file_name, $down_name, $content_type)
{	global $app_USER;
	$download 									= new download();
	$download->client 					= $app_USER->id;
	$download->content_type 		= $content_type;
	$download->created					= date("Y-m-d H:i:s");
	$download->down_name 				= $down_name;
	$download->expire						= date("Y-m-d H:i:s", time() + 1800);
	$download->file_name 				= $file_name;
	$download->INSERT();
	return $download->id;
}


function processSpecialPage()
{ //if(owns_acces(app::$user->id, $_REQUEST["special_page"], isset($_REQUEST["sys_action"]) ? $_REQUEST["sys_action"] : ""))
  //die(app::getInstance()->getCurentForm());
  if(owns_acces(app::getInstance()->getUser()->id, app::getInstance()->getCurentForm()))
  { require $_REQUEST["special_page"];
  } else
  { processor::denyUser(3);
  }
}

function processSpecialAppPage()
{ //if(owns_acces(app::$user->id, $_REQUEST["special_app_page"], isset($_REQUEST["sys_action"]) ? $_REQUEST["sys_action"] : ""))

  if(owns_acces(app::getInstance()->getUser()->id, app::getInstance()->getCurentForm()))
  { require $_REQUEST["special_app_page"];
  } else
  { processor::denyUser(3);
  }
}
function setVariable($varName, $varValue = "", $overwrite = true)
{

}



function bitwiseNOT($p1)
{ return ~p2;
}

function bitwiseAND($p1, $p2)
{ return $p1 & $p2;
}

function bitwiseOR($p1, $p2)
{ return $p1 | $p2;
}



function getAttribute($class, $item, $property)
{ $attrs             = new attribute();
  $attrs->class      = $class;
  $attrs->item       = $item;
  $attrs->property   = $property;
  $rsAttrs = new rowSet($attrs);
  if($rsAttrs->getRow($attrs))
  { return $attrs->value;
  }
}

function setAattribute($class, $item, $property, $value)
{ $attrs             = new attribute();
  $attrs2            = new attribute();
  $attrs->class      = $class;
  $attrs->item       = $item;
  $attrs->property   = $property;
  $rsAttrs = new rowSet($attrs);
  if($rsAttrs->getRow($attrs2))
  { $attrs2->value = $value;
    $attrs2->time   = date("Y-m-d H:i:s");
    return $attrs2->UPDATE();
  } else
  { $attrs->value = $value;
    $attrs->time   = date("Y-m-d H:i:s");
    return $attrs->INSERT();
  }

}

function getAttributes($class, $item)
{ $attrValues = array();
  $attrs = new attribute();
  $attrs->class = $class;
  $attrs->item  = $item;
  $rsAttrs = new rowSet($attrs);
  while($rsAttrs->getRow($attrs))
  { $attrValues[$attrs->property] = $attrs->value;
  }
  return $attrValues;
}

function putDocumentByYMD($document, $libraryRoot, $evaluatePathOnly = TRUE)
{
  $Y                           = date("Y");
  $m                           = date("m");
  $d                           = date("d");
  //$imageName                   = app::getInstance()->getUser()->id . "_" . time() . "_" . ba;
  $path = $libraryRoot . "/" . $Y;
  if(!file_exists($path))
  { //die($path);
    mkdir($path);
  }
  $path .=  "/" . $m;
  if(!file_exists($path))
  { mkdir($path);
  }
  $path .=  "/" . $d;
  if(!file_exists($path))
  { mkdir($path);
  }
  $path .=  "/" . basename($document);

  if($evaluatePathOnly)
  { return $path;
  } else
  { if(copy($document, $path))
    { return $path;
    }
  }
  return false;
}
